"use strict";

const UserModel = require("../../model/User");

class User {
  constructor() {
    this.getUser = this.getUser.bind(this);
    this.register = this.register.bind(this);
    this.isHasUser = this.isHasUser.bind(this);
  }

  //获取用户
  getUser(req, res, next) {
    UserModel.find({}, (err, docs) => {
      if (err) return res.json({ code: -1, err: err });
      res.json({
        code: 200,
        data: docs,
      });
    });
  }

  //   注册用户
  async register(req, res, next) {
    const body = req.body;

    if (!body.name) return res.json({ code: -1, msg: "请输入用户名！" });

    const flag = await this.isHasUser(req.body.name);

    if (!flag) return res.json({ code: -1, msg: "用户名已存在！" });

    UserModel.insertMany({ ...body }, (err) => {
      if (err) return res.json({ code: -1, err: err });
      res.json({
        code: 200,
        msg: "创建用户成功",
      });
    });
  }

  //   查询用户名是否存在
  async isHasUser(name) {
    const user = await UserModel.findOne({ name });
    if (user) return false;
    return true;
  }

  //   更新名字
  async updated(req, res, next) {
    const body = req.body;

    if (!body._id) return res.json({ code: -1, msg: "请选择需要修改的用户" });

    const flag = await this.isHasUser(req.body.name);

    if (!flag) return res.json({ code: -1, msg: "用户名已存在！" });

    UserModel.findByIdAndUpdate(
      body._id,
      { name: body.name, update_time: new Date() },
      {},
      (err, docs) => {
        if (err) return res.json({ code: -1, err: err });

        res.json({ code: 200, msg: "修改成功！" });
      }
    );
  }

  //   删除用户
  async delete(req, res, next) {
    const body = req.body;

    if (!body._id) return res.json({ code: -1, msg: "请选择需要删除的用户" });

    UserModel.findByIdAndRemove(body._id, {}, (err, docs) => {
      if (err) return res.json({ code: -1, err: err });

      res.json({ code: 200, msg: "删除成功！" });
    });
  }
}

module.exports = new User();
